package com.yvan.leto.listener;

import com.yvan.YvanUtil;
import com.yvan.leto.ConfigChangeEvent;
import com.yvan.leto.ConfigListener;
import com.yvan.leto.SegmentHelper;
import com.yvan.leto.boot.LetoSpringContext;
import com.yvan.platform.JsonWapper;
import lombok.SneakyThrows;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by xiaoEight on 2018/6/14.
 */
public class SpringBootListener implements ConfigListener {

    private static final AtomicBoolean IS_FIRST = new AtomicBoolean(true);

    @Override
    public String watchSegment() {
        return SegmentHelper.SPRING_BOOT;
    }

    @Override
    @SneakyThrows
    public void onChange(ConfigChangeEvent changeEvent) {
        final String yamlContent = changeEvent.getChanges();
        JsonWapper springJw = YvanUtil.readYaml(yamlContent);
        Map<String, Object> mapSource = (Map<String, Object>)springJw.getInnerMap();
        if(IS_FIRST.get()){
            LetoSpringContext.setBootMap(mapSource);
            IS_FIRST.compareAndSet(true,false);
        }

        Properties springProperties = new Properties();
        springProperties.putAll(springJw.getInnerMap());
        LetoSpringContext.setReloadProperties(springProperties);
        if(!IS_FIRST.get()){
            if(LetoSpringContext.getReloadablePropertyPostProcessor()!=null){
                LetoSpringContext.getReloadablePropertyPostProcessor().updatePropertiesOnBean();
            }
            if(LetoSpringContext.getElasticJobAutoConfiguration()!=null){
                LetoSpringContext.getElasticJobAutoConfiguration().updateCronOnBean();
            }
        }
    }
}
